const { http } = require("../modal/db.config");
const { getCurrentDateTime } = require("../modal/time.config");

const resolveDataFun = (list) => {
  list.forEach((v) => {
    list.forEach((a) => {
      if (v.id === a.parentId) {
        if (v.children === null) v.children = [];
        v.children.push(a);
      }
    });
  });
  list = list.filter((v) => v.rootId === '0');
  return list;
};

exports.create = async (req, res) => {
  const body = req.body;
  const { name, parentId, rootId } = body;
  const data = {
    id: Date.now(),
    name,
    parentId,
    rootId,
    create_time: getCurrentDateTime(),
    update_time: getCurrentDateTime(),
  };
  const newData = await req.services.CategoryService.create(data);
  if (newData.affectedRows === 1) {
    res.status(200).json({ data: "新增成功", msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "系统错误，请重试", msg: "fail", code: 500 });
  }
};

exports.list = async (req, res) => {
  const body = req.body;
  const { name = "" } = body;
  let newData = await req.services.CategoryService.findAll();
  newData = newData.map((v) => {
    v.children = null;
    return v;
  });
  const result = resolveDataFun(newData);

  res.status(200).json({
    data: result,
    msg: "success",
    code: 200,
  });
};

exports.update = async (req, res) => {
  const body = req.body;
  const { name, id } = body;
  const update_time = getCurrentDateTime();
  const data = {
    name,
    update_time,
  };
  const newData = await req.services.CategoryService.update(data, {
    id,
  });
  if (newData.affectedRows === 1) {
    res.status(200).json({ data: "更新成功", msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "系统错误，请重试", msg: "fail", code: 500 });
  }
};

exports.getDetail = async (req, res) => {
  const body = req.query;
  const { id } = body;
  const newData = await req.services.CategoryService.findById(id);
  if (newData) {
    res.status(200).json({ data: newData, msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "查无此人", msg: "fail", code: 400 });
  }
};

exports.del = async (req, res) => {
  const body = req.query;
  const { id } = body;
  const newData = await req.services.CategoryService.delete(Number(id));
  if (newData.affectedRows === 1) {
    res.status(200).json({ data: "删除成功", msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "查无此人", msg: "fail", code: 400 });
  }
};
